package com.airsystem.pos.bengkel.util;

import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTextField;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class Preconditions {

	public static <T> void checkNotNull(T data) {
		if (data == null) {
			throwIllegal();
		}
	}

	public static <T> void checkNotNull(T data, String message) {
		if (data == null) {
			throwIllegal(message);
		}
	}

	public static void checkEmpty(String data) {
		checkNotNull(data);

		if (data.isEmpty()) {
			throwIllegal();
		} else if (data.equals("-- PILIH --") || data.equals("-- PILIH PERIOD --")) {
			throwIllegal();
		}
	}

	public static void checkEmpty(String data, String message) {
		try {
			checkEmpty(data);
		} catch (IllegalArgumentException e) {
			throwIllegal(message);
		}
	}

	public static <T extends JComponent> void checkEmpty(T component) {
		checkNotNull(component);

		if (isCombo(component)) {
			if (((JComboBox) component).getSelectedIndex() == 0) {
				throwIllegal();
			}
		}

		if (isTextField(component)) {
			if (((JTextField) component).getText().trim().isEmpty()) {
				throwIllegal();
			}
		}
	}

	public static void checkState(boolean state, String message) {
		if (state) {
			throwIllegalState(message);
		}
	}

	private static <T extends JComponent> boolean isCombo(T component) {
		return component instanceof JComboBox;
	}

	private static <T extends JComponent> boolean isTextField(T component) {
		return component instanceof JTextField;
	}

	private static void throwIllegal() {
		throw new IllegalArgumentException();
	}

	private static void throwIllegal(String message) {
		throw new IllegalArgumentException(message);
	}

	private static void throwIllegalState(String message) {
		throw new IllegalStateException(message);
	}
}